package Controllers
{
	import Models.Model;
	import Models.OrderListItem;
	
	import mx.controls.Alert;
	import mx.controls.DataGrid;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.events.DataGridEvent;
	import mx.events.IndexChangedEvent;

	public class Controller
	{
		private var titleColumn : OrderListItem;
		private var referenceIdColumn : OrderListItem;
		private var documentIdColumn : OrderListItem;
		private var linkColumn : OrderListItem;
		
		public function Controller()
		{
			model = new Model();
			titleColumn = model.listItems.getItemAt(0) as OrderListItem;;
			referenceIdColumn = model.listItems.getItemAt(1) as OrderListItem;
			documentIdColumn = model.listItems.getItemAt(2) as OrderListItem;
			linkColumn = model.listItems.getItemAt(3) as OrderListItem;
		}
		
		public function GetModel() : Model
		{
			return model;
		}
		
		public function GetTitleColumn () : OrderListItem
		{
			return titleColumn;
		}
		
		public function GetReferenceIDColumn () : OrderListItem
		{
			return referenceIdColumn;
		}
		
		public function GetDocumentIdColumn () : OrderListItem
		{
			return documentIdColumn;
		}
		
		public function GetLinkColumn () : OrderListItem
		{
			return linkColumn;
		}
		
		public function OnHeaderShift(event:IndexChangedEvent):void
		{
			var newIndex : int = event.newIndex;
			var oldIndex : int = event.oldIndex;
			
			//if dragging to first place - put column as second
			if (newIndex == 0)
			{
				var dg:DataGrid = DataGrid(event.currentTarget);
				var columns : Array = dg.columns;
				var column:DataGridColumn = columns[0];
				columns[0] = columns[1];
				columns[1] = column;
				dg.columns = columns;
				newIndex = 1;
			}
			
			//update list items order (items do not contain number so - 1)
			newIndex--;
			oldIndex--;
			var item : OrderListItem = model.listItems[newIndex];
			model.listItems[newIndex] = model.listItems[oldIndex];
			model.listItems[oldIndex] = item; 
		}
		
		public function OnHeaderRelease(event:DataGridEvent) : void
		{
			for (var i : int = 0; i < model.listItems.length; i++)
			{
				var item : OrderListItem = model.listItems.getItemAt(i) as OrderListItem;
				var grid : DataGrid = DataGrid(event.currentTarget);
				var gridColumn : DataGridColumn = grid.columns[event.columnIndex] as DataGridColumn;
				
				if (gridColumn.headerText == item.title)
				{
					item.isSortedBy = true;
					item.isDescending = gridColumn.sortDescending;
				}
				else
				{
					item.isSortedBy = false;
				}
			}
		}
		
		private var model : Model;
	}
}